<template>
    <section>
        <div class="cate-container">
            <div class="header">
                <h4>商品编辑</h4>
            </div>
            <div class="good-con">
                <div class="good-con__title">
                    <i class="fa fa-angle-left" @click="back">&nbsp;返回所有商品列表</i>
                </div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                    <form-row :label="`商品名称`" :required="true" class="flex-box">
                        <el-form-item slot="item" class="form-row__item" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">建议：品牌 + 商品内容 + 规格</div>
                    </form-row>

                    <form-row :label="`商品简介`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="desc">
                            <el-input v-model="ruleForm.desc" placeholder="请输入商品简介"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">建议：简介并具有吸引力的文章</div>
                    </form-row>
                    <form-row label="商品主图" :required="true" prop="slideshows">
                        <div style="flex-direction:column;" class="flex-box">
                            <image-upload :imageList.sync="ruleForm.slideshow" :clearList="clearList"
                                          :imgNum="5">
                                <div slot="tip" class="image-info">尺寸750*600，支持jpg、png文件，5张上限</div>
                            </image-upload>

                        </div>
                    </form-row>
                    <form-row label="商品详情图" :required="true" prop="image">
                        <div style="flex-direction:column;" class="flex-box">
                            <upload :image.sync="ruleForm.image" :clearList="clearList">
                                <div slot="tip" class="image-info">尺寸宽度不低于640，高度不限制，支持jpg、png文件，1张上限</div>
                            </upload>
                        </div>

                    </form-row>

                    <form-row label="商品属性">
                        <AddAttrEdit :attrList.sync="attrList" :hash.sync="hash"/>
                    </form-row>

                    <form-row label="属性明细">
                        <!--<AttrDetailEdit :attrList="attrList" :hash="hash" @attr="renewAttr"/>-->
                        <AttrDetailEdit :attrList="attrList" :attrData="attrData" :hash="hash" @attr="renewAttr"/>

                    </form-row>

                    <form-row :label="`价格`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="sale_price">
                            <el-input v-model.number="ruleForm.sale_price" placeholder="请输入价格"
                                      :disabled="hasAttr"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">元</div>
                    </form-row>
                    <form-row :label="`是否售卖`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="is_on_sale">
                            <el-switch
                                    v-model="ruleForm.is_on_sale"
                                    active-color="#13ce66"
                                    inactive-color="#999999">
                            </el-switch>
                        </el-form-item>
                    </form-row>
                    <form-row :label="`单位`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="unit">
                            <el-input v-model.number="ruleForm.unit" placeholder="请输入单位"></el-input>
                        </el-form-item>
                    </form-row>

                    <form-row :label="`库存`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="number">
                            <el-input v-model.number="ruleForm.number" placeholder="请输入库存"
                                      :disabled="hasAttr"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">以单位中的规格来计算</div>
                    </form-row>
                    <form-row :label="`运费模板`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="freight_id">
                            <el-select v-model="ruleForm.freight_id" placeholder="请选择运费模板">
                                <el-option
                                        v-for="item in freightData"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </form-row>
                    <form-row style="border-bottom:none;">
                        <el-form-item slot="item" class="form-row__item_last">
                            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                        </el-form-item>
                    </form-row>

                </el-form>

            </div>
        </div>
    </section>
</template>

<script>
    import FormRow from '../../components/basic/FlowRow.vue';
    import ImageUpload from '../../components/basic/UploadImage/ImageUpload.vue'
    import Upload from '../../components/basic/UploadImage/Upload.vue';
    import CategoryList from '../../components/basic/CategoryList.vue';
    import AddAttrEdit from './components/AddAttrEdit'
    import AttrDetailEdit from './components/AttrDetailEdit'

    export default {
        components: {
            FormRow,
            Upload,
            CategoryList,
            ImageUpload,
            AddAttrEdit,
            AttrDetailEdit
        },
        data() {
            return {
                id: '',
                clearList: null,
                ruleForm: {
                    attributes: []
                },
                rules: {
                    name: [{required: true, message: '请填写商品名称', trigger: 'blur'}],
                    number: [{required: true, message: '请填写商品数量', trigger: 'blur'}, {
                        type: 'number',
                        message: '数量必须为数字'
                    }],
                    sale_price: [{required: true, message: '请填写商品价格', trigger: 'blur'}],
                    unit: [{required: true, message: '请填写单位', trigger: 'blur'}]
                },
                freightData: [],
                hash: Math.random(),
                attrList: [],
                attrData:[]
            }
        },
        computed: {
            hasAttr() {
                return this.ruleForm.attributes.length > 0
            }
        },
        watch:{

        },
        created() {
            this.id = this.$route.query.id;
            this.getGoodList(parseInt(this.$route.query.id));
            this.getAttrData(parseInt(this.$route.query.id));
            this.getFreightData();
        },
        mounted() {},
        methods: {
            back() {
                this.$router.go(-1);
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.resetForm.image = [];
                this.resetForm.slideshows = [];
                this.ruleForm.attributes = [];
                this.clearList = Math.random();
            },
            getGoodList(id) {
                axios
                    .get(`admin_goods/${id}`)
                    .then(res => res.data.data)
                    .then(res => {
                        console.log('数据', res.attributes)
                        this.attrData = res.attributes.map(res => {
                            // console.log('ko',{number: res.number,sale_price: res.sale_price,weight:res.weight})
                            return {number: res.number,sale_price: res.sale_price,weight:res.weight}
                            // return {number: 30,sale_price: 5,weight:8}
                            // return { [res.name]: res.value }

                        });
                        console.log('数据', this.attrData)
                        this.ruleForm = res;
                        this.ruleForm.is_on_sale = res.is_on_sale === 1 ? true : false;
                        this.ruleForm.slideshow = res.slideshow ? res.slideshow : [];
                        this.tableLoading = false;
                        console.log('转化', this.ruleForm)
                    })
            },
            getAttrData(id) {
                axios
                    .get('goods_attribute_type',{
                    params:{
                        goods_id:id
                    }
                })
                    .then(res => res.data.data)
                    .then(res => {
                        console.log('属性数据', res);
                        // const attrdata = this.ruleForm.attributes;
                        // for(var i=0 ; i < attrdata.length; i++){
                        //     res[i].number = attrdata[i].number;
                        //     res[i].weight = attrdata[i].weight;
                        //     res[i].sale_price = attrdata[i].sale_price
                        // }
                        this.attrList = res ? res : [];
                        // console.log('attrList值', this.attrList);
                    })
            },
            getFreightData() {
                axios
                    .get('admin_freights')
                    .then(res => res.data.data)
                    .then(res => {
                        this.freightData = res;
                    })
            },
            submitForm(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.$confirm('确认是否修改商品?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        })
                            .then(() => this.validate(this.ruleForm))
                            .then(() => this.postData())
                            .then(() => {
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                });
                            })
                            .catch(err => {
                                if (err !== 'cancel') {
                                    this.$message({
                                        type: 'error',
                                        message: `修改失败 ${err}`
                                    });
                                }
                            });
                    } else {
                        return false;
                    }
                });
            },
            validate(data) {
                const {image, slideshow, freight_id} = data;
                if (!image) return Promise.reject('请选择商品详情图');
                if (slideshow.length === 0) return Promise.reject('请选择商品主图');
                if (!freight_id) return Promise.reject('请选择运费模板')

                return data;
            },
            genData(data) {
                var attrNumber = 0;
                if (data.attributes.length > 0) {
                    for (var i = 0; i < data.attributes.length; i++) {
                        attrNumber += parseInt(data.attributes[i].number)
                    }
                }

                console.log('提交数据', data);
                const element = {
                    name: data.name,
                    number: data.attributes.length === 0 ? data.number : attrNumber,
                    sale_price: data.attributes.length === 0 ? data.sale_price : data.attributes[0].sale_price,
                    unit: data.unit,
                    is_on_sale: data.is_on_sale === true ? 1 : 0,
                    image: data.image ? data.image : '',
                    content_images: '',
                    desc: data.desc,
                    attributes: JSON.stringify(data.attributes),
                    slideshows: data.slideshow ? data.slideshow.map(res => res.url).join(',') : '',
                    cat_id: '',
                    freight_id: data.freight_id,
                    _method: 'PUT'
                };
                console.log('得到数据', element);
                return element;
            },
            postData() {
                return axios
                    .post(`admin_goods/${this.id}`, this.genData(this.ruleForm))
                    .then(res => {
                        return res.data.status === 1 ? Promise.resolve() : Promise.reject(res.data.msg);
                    });
            },
            //属性方法
            renewAttr(tableData) {
                const requiredKeys = ['sale_price', 'number', 'weight']
                const required = (data, list) => _.pick(data, list)
                const customize = (data, list) => _.omit(data, list)
                const genKey = data => _.map(data, (value, key) => ([key, value]))

                this.ruleForm.attributes = _.map(tableData, item => Object.assign({}, required(item, requiredKeys), {key: genKey(customize(item, requiredKeys))}))
                console.log('this.ruleForm.attributes',this.ruleForm.attributes)
            }
        }
    }
</script>
<style scoped>
    .cate-container {
        min-height: calc(100vh - 92px);
    }

    .flex-box {
        display: flex;
    }

    .header {
        padding: 10px;

        background: #FFFFFF;
    }

    .good-con {
        margin: 10px;
        padding: 20px;

        background: #ffffff;
    }

    .good-con__title {
        color: #3984F9;

        padding: 0 20px 20px 0;

        border-bottom: 1px dashed #D8D8D8;
    }

    .image-info {
        font-size: 12px;
        color: #666666;
        line-height: 33px;
        margin-left: 10px;
    }
</style>
<style>

</style>